package com.ruoyi.api.user;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.api.user.requestVo.SleepDailyDataRequestVo;
import com.ruoyi.api.user.requestVo.SleepDetailListSendRequestVo;
import com.ruoyi.api.user.requestVo.SleepDetailSendRequestVo;
import com.ruoyi.api.user.requestVo.SleepMonthlyDataRequestVo;
import com.ruoyi.api.user.requestVo.SleepSendRequestVo;
import com.ruoyi.api.user.requestVo.SleepWeeklyDataRequestVo;
import com.ruoyi.api.user.response.SleepDataResponseVo;
import com.ruoyi.api.user.response.SleepListResponseVo;
import com.ruoyi.api.util.DateUtil;
import com.ruoyi.framework.web.base.BaseController;
import com.ruoyi.user.domain.Machine;
import com.ruoyi.user.domain.Sleep;
import com.ruoyi.user.domain.SleepDetail;
import com.ruoyi.user.domain.Step;
import com.ruoyi.user.domain.User;
import com.ruoyi.user.service.IMachineService;
import com.ruoyi.user.service.ISleepDetailService;
import com.ruoyi.user.service.ISleepService;
import com.ruoyi.user.service.IStepService;

import io.swagger.annotations.ApiOperation;

/**
 * 问题反馈 信息操作处理
 * 
 * @author ruoyi
 * @date 2018-12-23
 */
@Controller
@RequestMapping("/api/sleep")
public class ApiSleepController extends BaseController
{
    private String prefix = "api:sleep";
	
	@Autowired
	private IStepService stepService;
	@Autowired
	private IMachineService machineService;
	@Autowired
	private ISleepService sleepService;
	@Autowired
	private ISleepDetailService sleepDetailService;
	
	/**
	 * 获取睡眠日数据
	 */
	@PostMapping("/daily")
	@ResponseBody
	@ApiOperation(value="获取睡眠日数据", notes="获取睡眠日数据",produces = "application/json")
	public HashMap<String, Object> daily(@RequestBody SleepDailyDataRequestVo dailyDataRequestVo)
	{		
		SleepDataResponseVo vo = new SleepDataResponseVo();
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
			Sleep param = new Sleep();
			param.setImei(dailyDataRequestVo.getCode());
			param.setSleepDate(sdf.parse(dailyDataRequestVo.getDateTime()));
			List<Sleep> list = sleepService.selectSleepList(param);
			if(list!=null&&list.size()>0){
				Sleep sleep = list.get(0);
				vo.setDeepSleep(sleep.getDeepCount());
				vo.setEasySleep(sleep.getEasyCount());
				if(sleep.getTotalCount()!=null&&sleep.getTotalCount()>0){
					vo.setTotalSleep(sleep.getTotalCount());
				}else{
					vo.setTotalSleep(sleep.getDeepCount()+sleep.getEasyCount());
				}
				vo.setLateSleep(sleep.getLateCount());
			}
			Machine paramMM = new Machine();
			paramMM.setCode(dailyDataRequestVo.getCode());
			List<Machine> listMM = machineService.selectMachineList(paramMM);
			if(listMM!=null&&listMM.size()>0){
				Machine ma = listMM.get(0);
				if(ma.getSource()==0){
					Step parm = new Step();
					parm.setImei(dailyDataRequestVo.getCode());
					String tomorrow = DateUtil.beforeDaysToDate(dailyDataRequestVo.getDateTime(), -1, "yyyy-MM-dd");
					parm.setCreateBy(dailyDataRequestVo.getDateTime()+" 21:00:00");
					parm.setUpdateBy(tomorrow+" 07:00:00");
					LinkedList<Step> listStep = stepService.selectSleepStepList(parm);
					for(Step s:listStep){
						SleepListResponseVo vv = new SleepListResponseVo();
						vv.setDate(sdf1.format(s.getCreateTime()));
						vv.setStatus(s.getType());
						vo.getList().add(vv);
					}
				}else{
					SleepDetail slpdParam = new SleepDetail();
					slpdParam.setImei(dailyDataRequestVo.getCode());
					slpdParam.setSleepDate(sdf.parse(dailyDataRequestVo.getDateTime()));
					List<SleepDetail> listSpld = sleepDetailService.selectSleepDetailList(slpdParam);
					for(SleepDetail slpd:listSpld){
						SleepListResponseVo vv = new SleepListResponseVo();
						vv.setDate(sdf1.format(slpd.getEndTime()));
						Integer type = slpd.getType();
						Integer status = 3;
						if(type.intValue()==0){
							status = 4;
						}else if(type.intValue()==2){
							status = 2;
						}else if(type.intValue()==3){
							status = 1;
						}else{
							status = 3;
						}
						vv.setStatus(status);
						vo.getList().add(vv);
					}
				}
			}else{
				Step parm = new Step();
				parm.setImei(dailyDataRequestVo.getCode());
				String tomorrow = DateUtil.beforeDaysToDate(dailyDataRequestVo.getDateTime(), -1, "yyyy-MM-dd");
				parm.setCreateBy(dailyDataRequestVo.getDateTime()+" 21:00:00");
				parm.setUpdateBy(tomorrow+" 07:00:00");
				LinkedList<Step> listStep = stepService.selectSleepStepList(parm);
				for(Step s:listStep){
					SleepListResponseVo vv = new SleepListResponseVo();
					vv.setDate(sdf1.format(s.getCreateTime()));
					vv.setStatus(s.getType());
					vo.getList().add(vv);
				}
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return successApp(vo);
	}
	
	/**
	 * 获取睡眠周数据
	 */
	@PostMapping("/weekly")
	@ResponseBody
	@ApiOperation(value="获取睡眠周数据", notes="获取睡眠周数据",produces = "application/json")
	public HashMap<String, Object> weekly(@RequestBody SleepWeeklyDataRequestVo weeklyDataRequestVo)
	{		
		HashMap<String, Object> map = new HashMap<String, Object>();
		LinkedList<SleepDataResponseVo> listVo = new LinkedList<SleepDataResponseVo>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int totalSleep = 0;
		int deepSleep = 0;
		int easySleep = 0;
		int lateSleep = 0;
		int count = 0;
		try {
			Date dBegin = sdf.parse(weeklyDataRequestVo.getBeginTime());
			Date dEnd = sdf.parse(weeklyDataRequestVo.getEndTime());
			List<String> datas = DateUtil.findDates(dBegin, dEnd);
			for(String day:datas){
				SleepDataResponseVo vo = new SleepDataResponseVo();
				vo.setDateTime(day);
				Sleep param = new Sleep();
				param.setImei(weeklyDataRequestVo.getCode());
				param.setSleepDate(sdf.parse(day));
				List<Sleep> list = sleepService.selectSleepList(param);
				if(list!=null&&list.size()>0){
					Sleep sleep = list.get(0);
					vo.setDeepSleep(sleep.getDeepCount());
					vo.setEasySleep(sleep.getEasyCount());
					if(sleep.getTotalCount()!=null&&sleep.getTotalCount()>0){
						vo.setTotalSleep(sleep.getTotalCount());
					}else{
						vo.setTotalSleep(sleep.getDeepCount()+sleep.getEasyCount());
					}
					/*vo.setTotalSleep(sleep.getDeepCount()+sleep.getEasyCount());*/
					vo.setLateSleep(sleep.getLateCount());
					totalSleep += vo.getTotalSleep().intValue();
					deepSleep += vo.getDeepSleep().intValue();
					easySleep += vo.getEasySleep().intValue();
					lateSleep += vo.getLateSleep().intValue();
					count++;
				}
				listVo.add(vo);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		count = count==0?1:count;
		map.put("list", listVo);
		map.put("total", totalSleep);
		map.put("avgTotal", totalSleep/count);
		map.put("avgDeep", deepSleep/count);
		map.put("avgEasy", easySleep/count);
		map.put("avgLate", lateSleep/count);
		return successApp(map);
	}
	
	/**
	 * 获取睡眠月数据
	 */
	@PostMapping("/monthly")
	@ResponseBody
	@ApiOperation(value="获取睡眠月数据", notes="获取睡眠月数据",produces = "application/json")
	public HashMap<String, Object> monthly(@RequestBody SleepMonthlyDataRequestVo monthlyDataRequestVo)
	{		
		HashMap<String, Object> map = new HashMap<String, Object>();
		LinkedList<SleepDataResponseVo> listVo = new LinkedList<SleepDataResponseVo>();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		int totalSleep = 0;
		int deepSleep = 0;
		int easySleep = 0;
		int lateSleep = 0;
		int count = 0;
		try {
			// Java8  LocalDate   
			ZoneId zoneId = ZoneId.systemDefault();
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
		    LocalDate date = LocalDate.parse(monthlyDataRequestVo.getMonthTime()+"-01");
		    // 该月第一天
		    LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
		    String zdtfirst = firstDay.format(formatter);
		    // 该月最后一天
		    LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());
		    String zdtlast = lastDay.format(formatter);
		    
			Date dBegin = sdf.parse(zdtfirst);
			Date dEnd = sdf.parse(zdtlast);
			List<String> datas = DateUtil.findDates(dBegin, dEnd);
			for(String day:datas){
				SleepDataResponseVo vo = new SleepDataResponseVo();
				vo.setDateTime(day);
				Sleep param = new Sleep();
				param.setImei(monthlyDataRequestVo.getCode());
				param.setSleepDate(sdf.parse(day));
				List<Sleep> list = sleepService.selectSleepList(param);
				if(list!=null&&list.size()>0){
					Sleep sleep = list.get(0);
					vo.setDeepSleep(sleep.getDeepCount());
					vo.setEasySleep(sleep.getEasyCount());
					if(sleep.getTotalCount()!=null&&sleep.getTotalCount()>0){
						vo.setTotalSleep(sleep.getTotalCount());
					}else{
						vo.setTotalSleep(sleep.getDeepCount()+sleep.getEasyCount());
					}
					/*vo.setTotalSleep(sleep.getDeepCount()+sleep.getEasyCount());*/
					vo.setLateSleep(sleep.getLateCount());
					totalSleep += vo.getTotalSleep().intValue();
					deepSleep += vo.getDeepSleep().intValue();
					easySleep += vo.getEasySleep().intValue();
					lateSleep += vo.getLateSleep().intValue();
					count++;
				}
				listVo.add(vo);
			}
		} catch (ParseException e) {
			e.printStackTrace();
		}
		count = count==0?1:count;
		map.put("list", listVo);
		map.put("total", totalSleep);
		map.put("avgTotal", totalSleep/count);
		map.put("avgDeep", deepSleep/count);
		map.put("avgEasy", easySleep/count);
		map.put("avgLate", lateSleep/count);
		return successApp(map);
	}
	
	/**
	 * 上传睡眠数据
	 */
	@PostMapping("/sendSleep")
	@ResponseBody
	@ApiOperation(value="上传睡眠数据", notes="上传睡眠数据",produces = "application/json")
	public HashMap<String, Object> sendSleep(@RequestBody SleepSendRequestVo requestVo)
	{		
		try {
			Sleep param = new Sleep();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			param.setImei(requestVo.getCode());
			param.setSleepDate(sdf.parse(requestVo.getMonthTime()));
			List<Sleep> list = sleepService.selectSleepList(param);
			if(list!=null&&list.size()>0){
				for(Sleep sl:list){
					sleepService.deleteSleepByIds(sl.getId().toString());
				}
			}
			Sleep sleep = new Sleep();
			sleep.setSleepDate(sdf.parse(requestVo.getMonthTime()));
			sleep.setCreateTime(sdf.parse(requestVo.getMonthTime()));
			sleep.setDeepCount(requestVo.getDeepCount());
			sleep.setEasyCount(requestVo.getEasyCount());
			sleep.setLateCount(requestVo.getLateCount());
			sleep.setTotalCount(requestVo.getTotalCount());
			sleep.setImei(requestVo.getCode());
			sleepService.insertSleep(sleep);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return errorApp("sl-0003","上传睡眠数据失败");
		}
		return successApp("");
	}
	
	/**
	 * 上传睡眠数据明细
	 */
	@PostMapping("/sendSleepDetail")
	@ResponseBody
	@ApiOperation(value="上传睡眠数据明细", notes="上传睡眠数据明细",produces = "application/json")
	public HashMap<String, Object> sendSleepDetail(@RequestBody SleepDetailSendRequestVo requestVo)
	{		
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			SleepDetail slpdParam = new SleepDetail();
			slpdParam.setImei(requestVo.getCode());
			slpdParam.setSleepDate(sdf.parse(requestVo.getMonthTime()));
			List<SleepDetail> listSpld = sleepDetailService.selectSleepDetailList(slpdParam);
			String ids = "";
			int count = 0 ;
			for(SleepDetail sld:listSpld){
				if(count==0){
					ids += sld.getId();
				}else{
					ids += ","+sld.getId();
				}
				count++;
			}
			sleepDetailService.deleteSleepDetailByIds(ids);
			List<SleepDetailListSendRequestVo> list = requestVo.getList();
			for(SleepDetailListSendRequestVo ls:list){
				SleepDetail sleepDetail = new SleepDetail();
				sleepDetail.setSleepDate(sdf.parse(requestVo.getMonthTime()));
				sleepDetail.setCreateTime(sdf.parse(requestVo.getMonthTime()));
				sleepDetail.setImei(requestVo.getCode());
				sleepDetail.setSleepCount(ls.getSleepCount());
				sleepDetail.setStartTime(sdf1.parse(ls.getStartTime()));
				sleepDetail.setEndTime(sdf1.parse(ls.getEndTime()));
				sleepDetail.setType(ls.getType());
				sleepDetailService.insertSleepDetail(sleepDetail);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return errorApp("sl-0004","上传睡眠明细数据失败");
		}
		return successApp("");
	}

}
